package com.cinema.api.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cinema.api.mapper.ActivityMapper;
import com.cinema.api.model.entity.Activity;
import com.cinema.api.model.entity.Registration;
import com.cinema.api.mapper.RegistrationMapper;
import com.cinema.api.model.enums.ResultCodeEnum;
import com.cinema.api.model.exception.BizException;
import com.cinema.api.service.RegistrationService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cinema.api.utils.BaseUtil;
import com.cinema.api.utils.DataTimeUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xhh
 * @since 2021-12-31
 */
@Service
public class RegistrationServiceImpl extends ServiceImpl<RegistrationMapper, Registration> implements RegistrationService {

    @Resource
    private RegistrationMapper registrationMapper;

    @Resource
    private ActivityMapper activityMapper;

    /**
     *  活动报名注册
     */
    @Override
    public void sign(Registration registration) {
        // 获取要报名的活动信息
        Activity activity = activityMapper.selectById(registration.getAid());
        if (BaseUtil.isEmpty(activity)) {
            throw new BizException(ResultCodeEnum.PARAM_ERROR);
        }
        // 判断用户是否已经参加过该活动
        QueryWrapper<Registration> wrapper = new QueryWrapper<>();
        wrapper.in("aid", registration.getAid())
                .in("uid", registration.getUid())
                .eq("is_delete", 0);
        Registration selectOne = registrationMapper.selectOne(wrapper);
        if (BaseUtil.isNotEmpty(selectOne)) {
            throw new BizException(2002, "您已报名参加此活动，请勿重复报名！");
        }
        // 通过，则活动报名人员+1
        activity.setNumber(activity.getNumber()+1);
        activityMapper.updateById(activity);
        // 更新报名注册表
        registration.setId(UUID.randomUUID().toString());
        registration.setCreateTime(DataTimeUtil.getNowTimeString());
        registration.setIsDelete(0);
        registrationMapper.insert(registration);
    }
}
